//
//  SPUserpicsPopUpButton.m
//  Sophie
//
//  Created by Moof on 10/22/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SPUserpicsPopUpButton.h"

@interface SPUserpicsPopUpButton (Private)
- (NSImage*)scaledImageFromImage:(NSImage*)image;
- (void)removeImage;
@end

@implementation SPUserpicsPopUpButton

- (void)setMenu:(NSMenu *)menu {
	[super setMenu:menu];
	[[self menu] setDelegate:self];
	[self menuDidClose:[self menu]];
	
}

- (void)menuDidClose:(NSMenu *)menu {
	for(int i = 0; i < [[menu itemArray] count]; ++i) {
		[[menu itemAtIndex:i] setImage:nil];
	}
}

- (NSInteger)numberOfItemsInMenu:(NSMenu *)menu {
	return [[menu itemArray] count];
}

- (BOOL)menu:(NSMenu *)menu updateItem:(NSMenuItem *)item atIndex:(NSInteger)index shouldCancel:(BOOL)shouldCancel {
	LJUserpic *userpic = [item representedObject];
	if (userpic) {
		[item setImage:[self scaledImageFromImage:[userpic image]]];
	}
	
	return YES;
}

- (NSImage*)scaledImageFromImage:(NSImage*)image {
	if (!image) {
		return nil;
	}
	NSImage* smallImage = [image copy];
	NSSize adjusdtedSize;
	// Set proportional size
	float h = [smallImage size].height;
	float w = [smallImage size].width;
	float scale = 1;
	if( MAX(h, w) > 30) {
		scale = 30 / MAX(h, w);
	}
	adjusdtedSize.height = h * scale;
	adjusdtedSize.width = w * scale;
	
	[smallImage setSize:adjusdtedSize];
	return [smallImage autorelease];
}

@end
